package com.lk.demo.controller;

import com.lk.demo.model.Author;
import com.lk.demo.model.Book;
import com.lk.demo.service.BookService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    private static final Logger log = LoggerFactory.getLogger(BookController.class);


    // Method: GET 请求路径：http://localhost:8080/book/{id}
    // 返回结果：{"author":"jk","name":"hello","price":100,"isbn":"1234567890","id":1}
    @GetMapping("/{id}")
    public Book get(@PathVariable Long id) {
        log.debug("Got HttpRequest, book id:{}", id);
        return bookService.get(id);
    }

    // Method: GET  请求路径：http://localhost:8080/book?name={name}&author={author}
    @GetMapping("")
    public List<Book> findBooks(@RequestParam String name, @RequestParam String author) {
        log.info("Got Request From Frontend, name:{}, author:{}", name, author);
        List<Book> books= bookService.findBooks(name, author);
        return books;
    }

    // Method: POST 请求路径：http://localhost:8080/book
    @PostMapping("")
    public Book save(@RequestBody Book book) {
        return bookService.save(book);
    }

    // Method: Put 请求路径：http://localhost:8080/book/{id}
    @PutMapping("/{id}")
    public Book update(@PathVariable Long id, @RequestBody Book book) {
        book.setId(id);
        return bookService.update(book);
    }

    // Method: Delete 请求路径：http://localhost:8080/book/{id}
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Long id) {

        return bookService.delete(id);
    }

    // method post 请求路径：http://localhost:8080/book/{bookId}/author/{authorId}
    @PostMapping("/{bookId}/author/{authorId}")
    public List<Author> addAuthor(@PathVariable Long bookId, @PathVariable Long authorId) {
        return bookService.addAuthor(bookId, authorId);
    }

    @DeleteMapping("/{bookId}/author/{authorId}")
    public List<Author> deleteAuthor(@PathVariable Long bookId, @PathVariable Long authorId) {
        return bookService.deleteAuthor(bookId, authorId);
    }
}